import { useEffect } from 'react';
import { View, Text, StyleSheet, Pressable, DeviceEventEmitter } from 'react-native';
import { useCurrent, useSetState } from '../../../common/hooks';
import ProductServer from '../../../common/service/ProductServer';
import util from '../../../common/utils/util';
import * as  FORM from '../../../components/Form';
import { RootView } from '../../../components/Layout';
import ScrollList from '../../../components/ScrollList';
import { CStyle, CColor, CFlex } from '../../../constant/css';

export default function Tab() {
    const [state, setState] = useSetState({
        tab: [
            {
                key: '出库',
                value: 1,
            },
            {
                key: '入库',
                value: 0,
            }
        ],
        index: 1,
        data: [],
    })

    const [ref, setRef] = useCurrent({
        page: 1,
        pageSize: 10,
        type: 1,

        refreshProduct: null,
    })

    useEffect(() => {
        loadData()
        const refreshProduct = DeviceEventEmitter.addListener('refreshProduct', () => {
            setRef({ page: 1 })
            loadData()
        })
        setRef({ refreshProduct })
        return () => {
            ref.refreshProduct?.remove?.()
        }
    }, [])

    const loadData = async () => {
        const { data } = state
        const { page, pageSize, type } = ref
        const params = {
            page,
            pageSize,
            type,
        }
        const [err, res] = await ProductServer.getProductStock(params)
        if (err) return util.showError(err)
        let result = res?.data?.result || []
        if (page > 1) {
            if (result.length < pageSize) {
                setParams({ page: -1 })
            }
            result = data.concat(result)
        }
        setState({
            data: result
        })
    }

    const chooseTab = (_) => {
        if (_.value === state.index) return
        setRef({ type: _.value, page: 1 })
        setState({ index: _.value })
        loadData()
    }

    const renderTab = () =>
        <View style={[CFlex.row, CFlex.cc]}>
            {
                state.tab.map(_ =>
                    <Pressable
                        style={[
                            styles.tabContainer,
                            {
                                borderColor: _.value === state.index ? CColor.Blue : CColor.Gray,
                                borderBottomWidth: 1,
                            }
                        ]} key={_.value}
                        onPress={() => chooseTab(_)}>
                        <Text
                            style={[styles.tabText,
                            {
                                color: _.value === state.index ? CColor.Blue : CColor.Black
                            }
                            ]}
                        >{_.key}</Text>
                    </Pressable>
                )
            }
        </View>

    const renderItem = ({ item, index }) => {
        const { product: p = {} } = item
        const singleLast = index === state.data.length - 1 && state.data.length % 2 === 1
        return (
            <View key={item.guid} style={{ flex: 1, margin: 2, backgroundColor: CColor.White }}>
                <FORM.ExpoImage
                    style={[styles.image, { height: singleLast ? 240 : styles.image.height }]}
                    contentFit="cover"
                    source={p.cover ? { uri: p.cover } : require('./../../../assets/404.svg')} />
                <View style={{ flex: 1, marginTop: 0, padding: 5 }}>
                    <View style={[CFlex.row, CFlex.sc]}>
                        <View style={[CStyle.tag, { marginRight: 5 }]}>
                            <Text style={{ color: CColor.White, fontSize: 9 }}>{p.pIp}</Text>
                        </View>
                        <Text numberOfLines={1} style={{ flex: 1, color: CColor.Black, fontWeight: 'bold' }}>
                            {p.name}
                        </Text>
                    </View>
                    <View style={[CFlex.row, CFlex.sc, { marginTop: 5 }]}>
                        <View>
                            <Text style={{ color: CColor.Black, fontSize: 12 }}>{`${p.sourceDesc} / `}</Text>
                        </View>
                        <View>
                            <Text style={{ color: CColor.Black, fontSize: 12 }}>{p.categoryDesc}</Text>
                        </View>
                    </View>
                    <View style={{ marginTop: 5 }}>
                        <Text style={{ color: CColor.Black, fontSize: 12 }}>{util.dayjs(item.orderDate).format('YYYY-MM-DD HH:mm')}</Text>
                    </View>
                    <View style={[CFlex.row, CFlex.cc, styles.stockCard]}>
                        <Text>以</Text>
                        <Text style={{ color: CColor.Red, fontWeight: 'bold', fontStyle: 'italic' }}> ￥{item.price} </Text>
                        <View style={[CStyle.tag, { backgroundColor: item.type ? CColor.Origin : CColor.Green, marginHorizontal: 2 }]}>
                            <Text style={{ color: CColor.White, fontSize: 9 }}>{item.type ? '成交' : '买入'}</Text>
                        </View>
                        <Text> <Text style={{ color: CColor.Blue, fontWeight: 'bold' }}>{item.total}</Text> 件 </Text>
                    </View>
                    <View style={[CFlex.row, CFlex.ee, { marginTop: 5 }]}>
                        <Text style={{ color: CColor.Red, fontStyle: 'italic', fontWeight: 'bold' }}>{`${item.type ? '+' : '-'}${item.sum}￥`}</Text>
                    </View>
                </View>
            </View>
        )
    }

    const renderList = () =>
        <ScrollList
            bg='#F5F5F5'
            data={state.data}
            renderItem={renderItem}
            numColumns={2}
            onRefresh={() => {
                const { page, pageSize } = ref
                setRef({ page: 1 })
                loadData()
            }}
            onLoadMore={() => {
                const { page, pageSize } = ref
                if (page === -1) return util.showInfo('O.0 老板跑路了,没有了~')
                setRef({ page: page + 1 })
                loadData()
            }}
        />

    return (
        <RootView>
            {renderTab()}
            {renderList()}
        </RootView>
    );
}

const styles = StyleSheet.create({
    tabContainer: {
        flex: 1,
        ...CFlex.cc,
        borderBottomColor: CColor.Gray,
        borderBottomWidth: 1,
        height: 50
    },
    tabText: {
        fontSize: 16,
        fontWeight: 'bold',
        color: CColor.Black,
    },
    image: {
        width: '100%',
        height: 120,
        borderTopLeftRadius: 5,
        borderTopRightRadius: 5,
    },
    stockCard: {
        marginTop: 5, borderWidth: 1, paddingVertical: 5, borderRadius: 5, borderColor: CColor.Gray,
    },
})
